package org.web.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yexi
 */
@WebServlet("/cookie_session")
public class CookieSessionServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 模拟和数据库中账号信息的匹配
        try {
            if (!"admin".equals(username)) {
                throw new RuntimeException("账号不存在");
            }
            if (!"1".equals(password)) {
                throw new RuntimeException("密码错误");
            }
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    req.getRequestDispatcher("/WEB-INF/views/homepage.jsp").include(req, resp);
                    return;
                }
            }
            // 往 request 作用域存入数据（只在一次请求中有效）
            req.setAttribute("username", username);
            // 往 Cookie 存入数据，写给浏览器
            Cookie cookie = new Cookie("username", username);
            // 设置 Cookie 存活时间，以秒为单位
            cookie.setMaxAge(60);
            // 把 Cookie 写回浏览器。本质就是设置响应头（在存活时间内同一个浏览器有效）
            resp.addCookie(cookie);
            // 往 session 中存入共享数据（在一次会话中有效）
            req.getSession().setAttribute("USERNAME_IN_SESSION", username);
            // 请求转发
            req.getRequestDispatcher("/WEB-INF/views/homepage.jsp").include(req, resp);
        } catch (Exception e) {
            req.setAttribute("errorMsg", e.getMessage());
            req.getRequestDispatcher("/cookie_session.jsp").include(req, resp);
        }

    }
}
